package dao

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
)

const TagIndexName = "tags_index"

type BizTag struct {
	Uid   int64    `json:"uid"`
	Biz   string   `json:"biz"`
	BizId int64    `json:"biz_id"`
	Tags  []string `json:"tags"`
}

type TagElasticDAO struct {
	client *elastic.Client
}

func NewTagElasticDAO(client *elastic.Client) TagDAO {
	return &TagElasticDAO{
		client: client,
	}
}

func (dao *TagElasticDAO) Search(ctx context.Context, uid int64, biz string, expression []string) ([]int64, error) {
	query := elastic.NewBoolQuery().Must(elastic.NewTermQuery("uid", uid),
		elastic.NewTermQuery("biz", biz), elastic.NewTermsQueryFromStrings("tags", expression...))

	resp, err := dao.client.Search(TagIndexName).Query(query).Do(ctx)
	if err != nil {
		return []int64{}, err
	}

	res := make([]int64, 0, len(resp.Hits.Hits))
	for _, hit := range resp.Hits.Hits {
		var tag BizTag
		err = json.Unmarshal(hit.Source, &tag)
		if err != nil {
			return []int64{}, err
		}
		res = append(res, tag.BizId)
	}
	return res, nil
}
